package main

import (
	"github.com/mongodb/mongo-go-driver/mongo"
	"github.com/mongodb/mongo-go-driver/mongo/clientopt"
	"context"
	"time"
	"fmt"
	"github.com/mongodb/mongo-go-driver/bson/objectid"
)

//记录任务的时间点
type TimePoint struct {
	StrartTime int64 `bson:"startTime"`
	EndTime    int64 `bson:"endTime"`
}

//一条日志
type LogRecord struct {
	JobName   string    `bson:"jobName"`   //任务名
	Command   string    `bson:"command"`   //命令
	Err       string    `bson:"err"`       //脚本错误
	Content   string    `bson:"content"`   //脚本输出
	TimePoint TimePoint `bson:"timePoint"` //执行时间点信息
}

func main() {
	var (
		client     *mongo.Client
		err        error
		database   *mongo.Database
		collection *mongo.Collection
		record     *LogRecord
		result     *mongo.InsertOneResult
		docId      objectid.ObjectID
	)
	if client, err = mongo.Connect(context.TODO(), "mongodb://106.12.21.94:27017", clientopt.ConnectTimeout(5*time.Second)); err != nil {
		fmt.Println(err)
		return
	}

	// 2, 选择数据库my_db ，没有自动创建
	database = client.Database("cron")

	// 3, 选择表my_collection 没有自动创建
	collection = database.Collection("log")

	//4插入记录(bson)
	record = &LogRecord{
		JobName: "job 10",
		Command: "echo hello",
		Err:     "",
		Content: "hello",
		TimePoint: TimePoint{
			StrartTime: time.Now().Unix(),
			EndTime:    time.Now().Unix() + 10,
		},
	}

	if result, err = collection.InsertOne(context.TODO(), record); err != nil {
		fmt.Println(err)
		return
	}
	docId = result.InsertedID.(objectid.ObjectID)
	fmt.Println("自增id:", docId.Hex())

}
